$(document).ready(function(){
    /*--------导入模块--------*/
    const api = require("./modules/api.js");
    const env = new nunjucks.Environment(new nunjucks.WebLoader('/views'));
    const url = require("url");
    const querystring = require("querystring");
    const moment = require("moment");
    /*--------获取id---------*/
    const id = window.location.pathname.split("/product/detail/")[1];

    
    const pagination_temp = env.getTemplate("pagination.html");
    const recodes_temp = env.getTemplate("recode_list.html");
    const rates_temp = env.getTemplate("rate_list.html");
    console.log(rates_temp)
    
    // 添加过滤器
    env.addFilter("formatDateTime", (timestamp, template)=>{
        return moment(timestamp).format(template);
    });

    /*--------声明变量------------*/
    // 商品详情
    let product = {};

    getDetail();
    // 购物车
    let type = $(".form-tags .tag").eq(0).data()["type"];
    // 获取默认类型
    console.log(type);
    


    let shopCart = {
        items: [{}],
        type: type
    };
    let quantity = 0;

    /*--------获取商品详情---------*/
    function getDetail(){
        api.product_detail(id).then(data=>{
            if(data.code == "0"){
                product = data.result;
                shopCart.items[0].itemId = data.result.id;
                shopCart.items[0].product = data.result;
                console.log(data.result);
                try{
                    product.discountsConfig = JSON.parse(data.result.discountsConfig);
                }catch(e){
                    product.discountsConfig = [];
                };

                let initPrice = "";
                console.log("type:",type);
                if(type == "PF"){

                    $(".unit-price").text(product.pfPrice);
                }else if(type == "TP"){
                    $(".unit-price").text(product.tpPrice);
                };
            };
        });
    };

    /*--------切换商品图片-----------*/
    $(".product-imgs .product-logo").each(function(index){
        $(this).mouseenter(function(){
            $(".product-imgs .product-logo").removeClass("active");
            $(this).addClass("active");
            let image_url = product.cover.split(",")[index];
            $("#view-logo").attr("src", image_url);
        });
    });

    /*--------切换导航栏-----------*/
    $(".product-navbar .nav-item").each(function(index){
        $(this).click(function(){
            $(".product-navbar .nav-item").removeClass("nav-item-active");
            $(this).addClass("nav-item-active");

            $(".product-content-section").removeClass("active");
            $(".product-content-section").eq(index).addClass("active");
        });
    });

    $(".form-tags .tag").eq(0).addClass("tag-active");
    /*--------切换加工方式---------*/
    $(".form-tags .tag").each(function(index){
        $(this).click(function(){
            $(".form-tags .tag").removeClass("tag-active").eq(index).addClass("tag-active");
            shopCart.type = $(this).data().type;
            
            computeDiscount();
        });
    });

    /*--------检测input输入-------*/
    $("#product-quantity").bind("input property", function(){
        computeDiscount();
    });
    
    function computeDiscount(){
        var val = $("#product-quantity").val();
        if(quantity_validator(val)){
            quantity = val;
            let discount = 1;
            for(let i = 0; i < product.discountsConfig.length; i ++){
                if(val <= product.discountsConfig[i].max){
                    discount = product.discountsConfig[i].discount;
                    return computeTotal(quantity, discount);
                }else if(val >= product.discountsConfig[product.discountsConfig.length - 1].max){
                    discount = product.discountsConfig[product.discountsConfig.length - 1].discount;
                    return computeTotal(quantity, discount);
                };
            };
        };
    };

    /*---------计算-----------*/
    function computeTotal(quantity, discount){
        console.log("discount: ", discount);
        let price = "";
        if(shopCart.type == "TP"){
            price = product.tpPrice;
        }else if(shopCart.type == "PF"){
            price = product.pfPrice;
        };
        let unit_price = (discount * price).toFixed(2);
        $(".unit-price").text(unit_price);

        let express_price = (quantity * product.unitFreight).toFixed(2);
        $(".unitFreight").text(express_price);
        
        let total_price = (discount * price * quantity + quantity * product.unitFreight).toFixed(2);
        console.log(total_price);
        $(".total-price").text(total_price);
    }

    /*--------提交表单----------*/
    $("#submit").click(function(){
        if(quantity_validator(quantity)){
            shopCart.items[0].quantity = quantity;
            localStorage.setItem("shopCart", JSON.stringify(shopCart));
            window.location.href = "/order/confirm";
        };
    });

    //验证表单
    function quantity_validator(val){
        console.log(quantity);
        if(!val){
            $("#product-quantity").nextAll(".error-message").text("请填写加工数量！").fadeIn();
            return false;
        };
        if(isNaN(val)){
            $("#product-quantity").nextAll(".error-message").text("请填写正确的数字！").fadeIn();
            return false;
        };
        if(val < product.minCount){
            $("#product-quantity").nextAll(".error-message").text(`加工数量不能小于${product.minCount}`).fadeIn();
            return false;
        };
        $("#product-quantity").nextAll(".error-message").text(`加工数量不能小于${product.minCount}`).fadeOut();
        return true;
    };

    //获取购买记录
    const recode_search = {
        productId: id,
        pageNo: 1,
        pageSize: 10
    };
    // 购买记录分页
    $("#recode-pagination").click(function(e){
        e.preventDefault();
        let href = e.target.href;
        if(href){
            let query = url.parse(href).query;
            let pageNo = querystring.parse(query).pageNo;
            recode_search.pageNo = pageNo;
            
            console.log(recode_search);
            getRecodes();
        }
        
    });

    // 获取购买记录
    function getRecodes(){
        api.product_orderRecord(recode_search).then(res=>{
            console.log(res);
            if(res.code == "0"){
                //渲染分页
                let page = res.result.page;
                let pageNo = recode_search.pageNo;
                let base_url = window.location.pathname;
                
                recode_pagination_render(page, pageNo, base_url);

                // 渲染列表
                let list = res.result.list || [];
                recode_render(list);
            };
        });
    };

    // 渲染分页记录翻页
    function recode_pagination_render(page, pageNo, base_url){
        pagination_temp.render({page, pageNo, base_url}, (err, html)=>{
            $("#recode-pagination").empty().append(html);
        });
    };

    // 渲染购买记录
    function recode_render(orderRecode_list){
        recodes_temp.render({orderRecode_list}, (err, html)=>{
            $("#recodes-list").empty().append(html);
        });
    };

    
    let rate_search = {
        productId: id,
        pageNo: 1,
        pageSize: 10
    };
    
    // 翻页
    $("#rate-pagination").click(function(e){
        e.preventDefault();
        let href = e.target.href;
        if(href){
            console.log(href);
            let query = url.parse(href).query;
            let pageNo = querystring.parse(query).pageNo;
            console.log(pageNo);
            rate_search.pageNo = pageNo;

            getRates();

        }
    });
    //获取评价
    function getRates(){
        api.product_rateList(rate_search).then(res=>{
            if(res.code == "0"){
                let page = res.result.page;
                let pageNo = rate_search.pageNo;
                let base_url = window.location.pathname;
                let list = res.result.list || [];
                rate_render(list);
                rate_pagination_render(page, pageNo, base_url);
            };
        });
    };
    // 渲染分页
    function rate_render(rateList){
        rates_temp.render({rateList}, (err, html)=>{
            $("#rateList").empty().append(html);
        });
    };
    // 渲染分页
    function rate_pagination_render(page, pageNo, base_url){
        pagination_temp.render({page, pageNo, base_url}, (err, html)=>{
            $("#rate-pagination").empty().append(html);
        });
    };
});